package com.pie4cloud.pie.job.biz.service.execute.impl;


import com.alibaba.fastjson.JSON;
import com.pie4cloud.pie.common.core.constant.SecurityConstants;
import com.pie4cloud.pie.common.core.util.R;
import com.pie4cloud.pie.job.api.dto.CallBackDto;
import com.pie4cloud.pie.job.api.dto.TriggerParam;
import com.pie4cloud.pie.job.api.entity.GatherEntity;
import com.pie4cloud.pie.job.api.entity.JobInfoEntity;
import com.pie4cloud.pie.job.api.feign.RemoteHandlerService;
import com.pie4cloud.pie.job.biz.config.FeignRemote;
import com.pie4cloud.pie.job.biz.gather.service.ConfigFtpService;
import com.pie4cloud.pie.job.biz.dao.GatherDao;
import com.pie4cloud.pie.job.biz.enums.ExecutorBlockStrategyEnum;
import com.pie4cloud.pie.job.biz.service.execute.ExecuteService;
import feign.Request;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequiredArgsConstructor
@Service("gatherService")
public class ExecuteGatherService extends ExecuteBaseService implements ExecuteService {

    @Autowired
    private GatherDao gatherDao;
	@Autowired
	private FeignRemote feignRemote;

	private final ConfigFtpService configFtpService;

    @Override
    public JobInfoEntity getById(Long id) {
		GatherEntity gatherEntity= gatherDao.findById(id).get();
        return gatherEntity;
    }

    @Override
    public void checkExecutorBlockStrategyEnum(JobInfoEntity jobInfoEntity) {
        jobInfoEntity.setExecutorBlockStrategy(ExecutorBlockStrategyEnum.TASK_SERIAL.name());
    }

	@Override
	public void remote(JobInfoEntity jobInfoEntity, R<String> resultT) {
		RemoteHandlerService remoteHandlerService=feignRemote.target(RemoteHandlerService.class,"pie-job-executor");
		TriggerParam triggerParam=new TriggerParam();
		triggerParam.setHanlder(jobInfoEntity.getExecutorHandler());
		triggerParam.setParams(JSON.toJSONString((GatherEntity)jobInfoEntity));
		triggerParam.setType(jobInfoEntity.getType());
		long startTime=new Date().getTime();

		try {
			Request.Options options =new Request.Options(2, TimeUnit.MINUTES,2,TimeUnit.MINUTES,true);
			resultT = remoteHandlerService.execute(options,triggerParam, SecurityConstants.FROM_IN);
		} catch (Exception e) {
			long endTime=new Date().getTime();
			log.info("耗时{}",endTime-startTime);
			e.printStackTrace();
			resultT.setCode(309);
			try {
				Thread.sleep(30*1000);
			} catch (InterruptedException interruptedException) {
				interruptedException.printStackTrace();
			}
		}
	}

	@Override
	public void callBack(CallBackDto callBackDto) {
		GatherEntity gatherEntity=JSON.parseObject(callBackDto.getParams(),GatherEntity.class);
		gatherDao.saveNotNull(gatherEntity);
	}
}

